package com.rookieCi.qrcodefile;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.lsjwzh.widget.materialloadingprogressbar.BuildConfig;
import com.rookieCi.qrcodefile.sync.SendFileActivity;
import com.rookieCi.qrcodefile.utils.LoadDialogUtils;
import com.rookieCi.qrcodefile.utils.Logger;
import com.rookieCi.qrcodefile.utils.PrivateFileUtils;
import com.rookieCi.qrcodefile.utils.ZipUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SendFileTmpActivity extends AppCompatActivity {
    @BindView(R.id.layoutFrame)
    public FrameLayout layoutFrame;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        ButterKnife.bind(this);

        setTitle("开始发送");

        Intent intent = getIntent();

        String action = intent.getAction();
        if (Intent.ACTION_SEND.equals(action)) {
            Bundle bundle = intent.getExtras();
            if (bundle == null) return;
            Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
            if (uri == null) return;//content://media/external/file/50489
            filePath = getRealPathFromUri(QrApp.getInstance(), uri);
        }
        layoutFrame.postDelayed(this::startFileCount, 100);
    }

    private void startFileCount() {
        if (TextUtils.isEmpty(filePath)) {
            onBackPressed();
        } else if (checkFilePermissions()) {
            openFile();
        }
    }

    private String filePath;//文件路径
    private static final long _1k = 1024L;
    private static final long _1M = _1k * 1024L;
    private static final long _1G = _1M * 1024L;
    private LoadDialogUtils dialogUtils;

    @Override
    protected void onDestroy() {
        if (dialogUtils != null) {
            dialogUtils.dismissDialog();
        }
        super.onDestroy();
    }

    /**
     * 打开文件
     */
    private void openFile() {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            new Thread(this::openFile).start();
            return;
        }
        if (TextUtils.isEmpty(filePath)) return;
        File file = new File(filePath);
        if (file.exists()) {
            long length = file.length();
            if (length > _1M * 100) {
                runOnUiThread(() -> openDialog(length));
                return;
            }
            String lowerName = file.getName().toLowerCase();
            if (lowerName.endsWith(".zip") || lowerName.endsWith(".rar") || lowerName.endsWith(".jar")) {
                useHintDialog(file);
                return;
            }
            if (dialogUtils == null) dialogUtils = new LoadDialogUtils(this);
            runOnUiThread(() -> dialogUtils.openLoadDialog("处理文件中"));

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                int read;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) > 0) {
                    outputStream.write(bytes, 0, read);
                }
            } catch (FileNotFoundException e) {
                if (BuildConfig.DEBUG) e.printStackTrace();
            } catch (IOException e) {
                if (BuildConfig.DEBUG) e.printStackTrace();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            int size = outputStream.size();
            if (size <= 0) {
                runOnUiThread(() -> {
                    dialogUtils.dismissDialog();
                    openDialog("加载失败，没救了告辞");
                });
                return;
            }
            byte[] bytes = outputStream.toByteArray();
            byte[] zip = ZipUtils.zip(bytes);
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bytes = null;
            outputStream = null;
            PrivateFileUtils fileUtils = new PrivateFileUtils(this, file.getName() + ".xcczip");
            fileUtils.setByte(zip);
            File zipFile = new File(fileUtils.getFilePath());
            if (!zipFile.exists() || zipFile.length() > length) {
                useHintDialog(file);
            } else {
                useHintDialog(zipFile);
            }
        } else {
            runOnUiThread(() -> openDialog("文件不见了！！！"));
        }
    }

    private void openDialog(long length) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("这么大？")
                .setMessage(length > _1G ? "1G文件至少需要传输124天，你想传多少天！！！" : "文件超过100M，放弃吧")
                .setPositiveButton("确定", null)
                .create();
        alertDialog.setOnDismissListener(dialog -> onBackPressed());
        alertDialog.show();
    }

    private void openDialog(String text) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("呵呵哒")
                .setMessage(text)
                .setPositiveButton("确定", null)
                .create();
        alertDialog.setOnDismissListener(dialog -> onBackPressed());
        alertDialog.show();
    }

    private void useHintDialog(File file) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            if (dialogUtils != null) dialogUtils.dismissDialog();

            long length = file.length();
            long s = length / 100;
            String msg;
            if (s > 60) {
                long m = s / 60;
                s = s % 60;
                if (m > 60) {
                    long h = m / 60;
                    m = m % 60;
                    msg = "预计需要" + h + "时" + m + "分" + s + "秒";
                } else msg = "预计需要" + m + "分" + s + "秒";
            } else msg = "预计需要" + s + "秒";
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("准备完成")
                    .setMessage(msg)
                    .setNegativeButton("放弃了", (dialog, which) -> onBackPressed())
                    .setPositiveButton("发送", (dialog, which) -> {
                        Intent intent = new Intent(SendFileTmpActivity.this, SendFileActivity.class);
                        intent.putExtra("sendType", 2);
                        intent.putExtra("text", file.getAbsolutePath());
                        startActivity(intent);
                        onBackPressed();
                    }).create();
            alertDialog.show();
        } else runOnUiThread(() -> useHintDialog(file));
    }

    private boolean checkFilePermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0xFF01);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0xFF01) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFile();
            } else {
                Toast.makeText(this, "不给权限拉倒~~", Toast.LENGTH_SHORT).show();
                onBackPressed();
            }
        } else super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            Logger.out("getRealPathFromUri: " + contentUri);
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if (cursor != null && cursor.getColumnCount() > 0) {
                cursor.moveToFirst();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String path = cursor.getString(column_index);
                Logger.out("getRealPathFromUri: column_index=" + column_index + ", path=" + path);
                return path;
            } else {
                Logger.out("getRealPathFromUri: invalid cursor=" + cursor + ", contentUri=" + contentUri);
            }
        } catch (Exception e) {
            Logger.out("" + e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
}
